# !/usr/bin/env python
# File       : auth.py
# Time       : 2022/8/29 15:15
# Author     : hyx
# -*- coding:utf-8 -*-
# 用户
import json
import os
import random
import string
import time
from datetime import datetime

from flask import Blueprint, render_template, request, redirect, url_for, jsonify, session, flash, g
from werkzeug.security import generate_password_hash, check_password_hash
from flask_mail import Message
from werkzeug.utils import secure_filename

from bluelog.decorators import login_required
from config import ALLOWED_EXTENSIONS, UPLOAD_FOLDER
from ext import db, mail, csrf
from forms import LoginForm, RegisterForm, EmailCaptchaModel, UpdateForm,UpdateAdmForm
from modle import UserModel

auth = Blueprint('auth', __name__)


# 登陆和注册
@auth.route('/login/', methods=['GET', 'POST'])
def login():
    print('登录界面')
    login_form = LoginForm(request.form)
    register_form = RegisterForm(request.form)
    if request.method == 'POST':
        # 判断是否是登陆
        is_login, is_regist = login_form.validate(), register_form.validate()
        if is_login and not is_regist:
            email = request.form.get('email')
            password = request.form.get('password')
            user = UserModel.query.filter_by(email=email).first()
            if user and check_password_hash(user.password, password):
                session['user_id'] = user.id
                flash('成功登陆', 'info')
                return redirect('/')
            else:
                if not user:
                    flash('邮箱未注册', 'danger')
                else:
                    flash('邮箱或密码不匹配', 'warning')
        # 判断是否为注册
        elif is_regist and not is_login:
            n_email = register_form.reg_email.data
            n_password = register_form.reg_password.data
            # 对明文密码进行加密
            hash_password = generate_password_hash(n_password)
            # 注册用户
            user = UserModel(password=hash_password, username=f'游客{n_email[:3]}', email=n_email)
            db.session.add(user)
            db.session.commit()
            flash('成功注册', 'success')
        else:
            # 如果没有通过login校验，并且有值
            if not is_login and len(request.form.get('reg_password', '')):
                flash('登陆的信息格式出错了,密码需要6位以上', 'warning')
            else:
                flash('输入有误，请重新检查填入的信息', 'danger')
        return redirect(url_for("auth.login"))
    return render_template('login.html', login_form=login_form, regist_form=register_form)


# 发送验证码
@csrf.exempt
@auth.route('/sentcaptcha/', methods=['POST'])
def sentcaptcha():
    print('进入')
    data = request.get_data()
    email = json.loads(data)['reg_email']
    letters = string.ascii_letters + string.digits
    captcha = ''.join(random.sample(letters, 4))
    print(captcha)
    print(json.loads(data))
    print(email)
    htmls = """
    <div style="position: relative;display: flex;flex-direction: column;align-items: center;justify-content: center;width: 80vmin;height: 80vmin;background: #d4dacd;padding: 5vmin;border-radius: 2vmin;">
        <h2 style="font-size: 6vmin;line-height: 110%;font-weight: 600;color: black;text-align: center;">注册验证码</h2>
        <p style="font-size: 4vmin;line-height: 150%;font-weight: 400;color: black;padding-left: 8vmin;border-left: 2px solid navy;margin: 6vmin 0;margin:0 auto;">
            尊敬的用户:
            我们收到了一项请求，要求通过你的电子邮箱地址，进行对我们站的注册。
            <br>
            您正在注册,您的验证码为:<b>{}</b>
            <br>
            此邮件无需回复，如有疑问请联系工作人员。
        </p>
    </div>
    """
    if email:
        message = Message(
            subject='邮箱测试',
            recipients=[email],
            body=htmls.format(captcha)
        )
        mail.send(message)
        print('开始发送')
        captcha_model = EmailCaptchaModel.query.filter_by(email=email).first()
        if captcha_model:
            print('已经存在了，更新验证码')
            captcha_model.captcha = captcha
            captcha_model.create_time = datetime.now()
            db.session.commit()
        else:
            print('创建验证码表')
            captcha_model = EmailCaptchaModel(email=email, captcha=captcha)
            db.session.add(captcha_model)
            db.session.commit()
        return jsonify({"code": 200})
    else:
        print('发送失败')
        return jsonify({'code': 400, "message": '服务器错误'})


# 注销
@auth.route('/logout/')
def logout():
    session.clear()
    flash('成功注销', 'info')
    return redirect(url_for('article.home'))


def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


# 个人的修改
@auth.route('/alter/<uuid:uuid>', methods=['GET', 'POST'])
@login_required
def alter(uuid):
    user = UserModel.query.filter_by(user_uuid=uuid).first()
    if request.method == "POST" and g.user == user:
        if 'avatar' not in request.files:
            flash('保存成功,但没有改变头像','info')
        file = request.files['avatar']
        if file.filename == '':
            flash('保存成功,但没有改变头像','info')
        # 修改头像
        if file and allowed_file(file.filename):
            filename = str((int(time.time()))) + secure_filename(file.filename)
            user_icon = f'img/user_icon/{user.id}/{filename}'
            img_path = UPLOAD_FOLDER + f'/img/user_icon/{user.id}'
            if not os.path.exists(img_path):
                os.mkdir(img_path)
            file_path = os.path.join(img_path, filename)
            # 删除上一个头像文件
            befor_user_icon = user.icon
            if befor_user_icon:
                path = UPLOAD_FOLDER + '/' + befor_user_icon.replace('\\', '/')
                if os.path.exists(path):
                    os.remove(path)
            # 修改头像
            user.icon = user_icon
            file.save(file_path)
        # 修改用户名
        user_name = request.form.get('username')
        upform = UpdateAdmForm(username=user_name)
        if upform.validate():
            user.username = user_name
        else:
            flash('用户名长度需在1-20之间','danger')
        db.session.commit()
        return redirect(url_for('auth.alter', uuid=uuid))
    if request.method == 'GET':
        return render_template('alter_data.html', user=user)


# 忘记密码
@auth.route('/forget/pawd',methods=['GET','POST'])
def forget_passwd():
    form = UpdateForm(request.form)
    if request.method =="POST":
        if form.validate():
            email = form.reg_email.data
            reg_password = form.reg_password.data
            user = UserModel.query.filter_by(email=email).first()
            user.password = generate_password_hash(reg_password)
            db.session.commit()
            flash('修改密码成功','info')
            return redirect(url_for('auth.login'))
        else:
            flash('修改失败','danger')
            return redirect(request.url)
    return render_template('forget_passwd.html',form=form)